import styles from './style.less';
import moment from 'moment';
import React, { useState, useEffect } from 'react';
import { Popover, Badge, Space, Empty } from 'antd';
import FullScreen from '@/components/FullScreen'
import { parseDate, formetDate } from '@/utils/dateUtils'



const TaskLane = (props) => {
    const {
        taskItem,
        totalLength,
        dateList
    } = props;

    const [taskLength, setTaskLength] = useState(0);
    const [beginPlace, setBeginPlace] = useState(0)

    useEffect(() => {
        if (taskItem && taskItem.startDate && taskItem.endDate) {
            let beginDate = dateList[0]
            let start = moment(taskItem.startDate, 'yyyy-MM-DD');
            let end = moment(taskItem.endDate, 'yyyy-MM-DD');
            let days = end.diff(start, "days");
            let beginPlaceDays = start.diff(beginDate, "days");
            let taskLength = (days < 0 ? 1 : days + 1);
            if (beginPlaceDays < 0) {
                taskLength = taskLength + beginPlaceDays;
                beginPlaceDays = 0;
            }
            if (beginPlaceDays + taskLength > totalLength) {
                taskLength = totalLength - beginPlaceDays;
            }
            setTaskLength(taskLength);
            setBeginPlace(beginPlaceDays)
        }
    }, [dateList, taskItem])

    const contentRender = (
        <Space direction="vertical">
            <Badge color={'green'} text={'开始时间:' + (formetDate(taskItem.startDate) || '')}></Badge>
            <Badge color={'blue'} text={'结束时间:' + (formetDate(taskItem.endDate) || '')}></Badge>
        </Space>
    )
    return (
        <div className={styles.task} style={{
            width: totalLength * 36
        }}>
            <Popover placement="topLeft" title={taskItem.name} content={contentRender}>
                <div className={styles.taskPrograss} style={{
                    width: 36 * taskLength,
                    marginLeft: 36 * beginPlace,
                }}></div>
            </Popover>
        </div>);
}

const TaskCalender = (props) => {
    const [months, setMonths] = useState({});
    const {
        showWeekDay,
        showMonth,
        dateList,
    } = props;


    useEffect(() => {
        if (dateList && dateList.length > 0) {
            let months = {}
            dateList.forEach(element => {
                let month = element.format('yyyy年MM月');
                if (!months[month]) {
                    months[month] = [];
                }
                months[month].push(element)
            });
            setMonths(months)
        }
        // scrollToAnchor('20201030');
    }, [dateList])

    const scrollToAnchor = (anchorName) => {
        if (anchorName) {
            let anchorElement = document.getElementById(anchorName);
            if (anchorElement) {
                anchorElement.scrollIntoView();
            }
        }
    }

    const headDateListRender = (dateList) => (
        dateList.map(item => {
            return (
                <div key={item.format('yyyyMMDD')} className={item.format('yyyyMMDD') == moment().format('yyyyMMDD') ? styles.calenderHeaderToday : styles.calenderHeaderDay} id={item.format('yyyyMMDD')}>
                    <div style={{
                        height: showWeekDay ? 28 : 27
                    }}>{item.format('D')}</div>
                    {showWeekDay ? (<div className={styles.weekClassName}>周 {item.isoWeekday()}</div>) : ''}
                </div>
            )
        })
    );

    const headMonthDateListRender = (
        Object.keys(months).map((key) => {
            return (<div key={key} >
                <div className={styles.monthHeader}> {key} </div>
                <div className={styles.calenderDayHeader}>{headDateListRender(months[key])}</div>
            </div>
            )
        })
    );

    return (
        <div>
            <div className={styles.calenderHeader} >{showMonth ?
                headMonthDateListRender :
                headDateListRender(dateList)}</div>
        </div>)
}



const Gantt = (props) => {
    const {
        showWeekDay = true,
        showMonth = true,
        taskHeaderFix = true,
        title,
        description,
        ganttId,
        taskData,
        columns = [],
        onTaskClick
    } = props;
    const [dateList, setDateList] = useState([])



    useEffect(() => {
        setDateList(getDateList(taskData));
    }, [taskData])

    const taskRender = taskData?.map(item => {
        return <TaskLane dateList={dateList} key={item.id} taskItem={item} totalLength={dateList.length}></TaskLane>
    })

    const tastListHeaderRender = (column) => {
        return taskData?.map(item => {
            if (column.render) {
                return <div key={item.id} style={{
                    width: column.width || "80px"
                }} className={styles.taskInfoItem}>{column.render(item)}</div>
            }
            const contentRender = (
                <Space direction="vertical">
                    <Badge color={'green'} text={'开始时间:' + (formetDate(item.startDate) || '')}></Badge>
                    <Badge color={'blue'} text={'结束时间:' + (formetDate(item.endDate) || '')}></Badge>
                </Space>
            )
            return (
                <Popover key={`${item.id}`} placement="topLeft" title={item[column.name]} content={contentRender}>
                    <div key={item.id} className={styles.taskInfoItem} style={{
                        width: column.width || "80px"
                    }}><span>{item[column.name]}</span></div>
                </Popover>
            )
        })
    }

    const getDateList = (taskData) => {
        let startDate = moment();
        let endDate;
        for (let index in taskData) {
            let taskStartDate = parseDate(taskData[index].startDate)
            let taskEndDate = parseDate(taskData[index].endDate)
            if (taskStartDate && startDate.isAfter(taskStartDate)) {
                startDate = taskStartDate
            }
            if (taskEndDate) {
                if (!endDate) {
                    endDate = taskEndDate
                } else if (endDate.isBefore(taskEndDate)) {
                    endDate = taskEndDate
                }
            }
        }
        if (!endDate) {
            endDate = moment().add(26, 'd');
        } else {
            let days = endDate.diff(startDate, "days");
            console.log(days)
            if (days < 30) {
                endDate = endDate.add(30 - days, 'd');
            } else {
                endDate = endDate.add(3, 'd');
            }
        }
        startDate = startDate.add(-3, 'd')

        const headDateList = [];
        let tempDate = startDate;
        headDateList.push(startDate)
        while (tempDate.isBefore(endDate)) {
            tempDate = moment(tempDate.format('yyyy-MM-DD'), 'yyyy-MM-DD').add(1, 'd');
            headDateList.push(tempDate);
        }
        return headDateList;
    }

    const taskHeadPlace = (
        <div style={{
            height: (showMonth ? 22 : 0) + (showWeekDay ? 20 : 0)
        }} className={styles.taskHeadPlaceClass}></div>
    );

    const taskBodyStyle = taskHeaderFix ? {} : {
        whiteSpace: "nowrap",
        overflowY: "scroll"
    };
    const taskLaneBodyStyle = taskHeaderFix ? {
        whiteSpace: "nowrap",
        overflowY: "scroll"
    } : {};

    return (<div id={ganttId} className={styles.container}>
        <div className={styles.ganttTitle}>
            <div style={{
            }}>
                {title}
            </div>
            <div className={styles.ganttDescription}>
                {description}
            </div>
            <div style={{
                position: 'absolute',
                right: 16,
                top: 0
            }}>
                <FullScreen containId={ganttId} ></FullScreen>
            </div>
        </div>
        <div>
            <div className={styles.taskBody} style={taskBodyStyle}>
                {columns && (
                    <div className={styles.taskList}>
                        {columns.map((column => {
                            return (<div key={column.name}>
                                <div className={styles.taskListHeader}>
                                    {taskHeadPlace}
                                    <div className={styles.taskListName}>
                                        {column.title}
                                    </div>
                                </div>
                                <div className={styles.taseListHeaderValue}>
                                    {tastListHeaderRender(column)}
                                </div>
                            </div>)
                        }))}
                    </div>
                )}
                <div className={styles.taskLaneBody} style={taskLaneBodyStyle}>
                    <TaskCalender showWeekDay={showWeekDay} showMonth={showMonth} dateList={dateList}></TaskCalender>
                    {(taskData && taskData.length > 0 && dateList) && (
                        <div>
                            {taskRender}
                        </div>
                    )}
                </div>
            </div>
            {(!taskData || taskData.length === 0) && <div className={styles.emptyTaskLaneClassName}>
                <Empty>

                </Empty>
            </div>}
        </div>
    </div>)
}


export default Gantt;

